home *** CD-ROM | disk | FTP | other *** search
- Path: else.net!tor250!org!gryn!fknights!andrew.frank
- From: Andrew.Frank@fknights.gryn.org (Andrew Frank)
- Date: 29 Jan 96 16:50:51
- Newsgroups: comp.lang.c
- Subject: Re: Finding a prime number
- Message-ID: <7c8_9601301722@tor250.org>
- References: <4e875s$nqk@reader2.ix.netcom.com>
- X-FTN-To: advtr@ix.netcom.com
- Organization: fks Online! * Ontario, Canada * (905)820-7273 *
-
- As advtr@ix.netcom.com had made knowen to All, on 25 Jan 96 10:21:32, I
- quote.
- ad> From: advtr@ix.netcom.com(Advance Trading)
- ad> Subject: Finding a prime number
- ad> Organization: Netcom
-
- ad> I need to write a function that will find wether or not a number is
- ad> prime. I can come close but I get numbers that are not prime with the
- ad> prime numbers.
-
- I recently wrote a program to do this. It will take about 10
- seconds to process a little at the start, but will then quickly tell
- if any number between 4 and 4.2 billion is prime. Here is the
- source code.
-
- ---------------- Code Start __________________
- /* Filename: PRIMETST.C */
- /* Tests to see if a given number is prime. */
- /* Requires a few seconds at startup to determine the low primes */
- #include <stdio.h>
- #include <stdlib.h>
-
- main()
- {
- unsigned long int I;
- unsigned int J;
- unsigned int P = 1;
- int PRIME = 1;
- unsigned int STACK[6670];
-
- puts("Generating Primes...");
-
- /* Is currently generating all prime numbers below 65535, uses
- these to test higher numbers for primeness. */
-
- STACK[0] = 2;
- for (I = 3; I < 65535; I += 2)
- { for (J = 1; (long int)STACK[J] * (long int)STACK[J] <= I;
- J++)
- { if (!(I % STACK[J]))
- { PRIME = 0;
- break;
- }
- }
- if (PRIME)
- { P++;
- STACK[P] = I;
- }
- PRIME = 1;
- }
- puts("Done.");
-
- while(1)
- {
- puts("Enter a number to test (under 4.2 billion), 0-3 quits");
- scanf(" %ul", &I);
- if (I < 4)
- { exit(1);}
-
- /* Tests inputted number against previous primes up until
- the square root of the number your checking */
-
- for (J = 0; (long int)STACK[J] * (long int)STACK[J] <= I; J++)
- {
- if (!(I % STACK[J]) && !(I / STACK[J] == 1))
- { PRIME = 0;
- break;
- }
- }
-
- if (PRIME)
- puts("Prime!");
- if (!(PRIME))
- puts("Not Prime.");
-
- PRIME = 1;
- }
- return 0;
- }
- -------------------- End Program Listing ----------------------
-
- There. Just cut between the lines, and compile it. It's most
- efficient if you have many numbers to test. There is a simpler and
- faster way if you only have one number to test (although this is
- reasonably simply for you because all you have to do now is cut and
- compile).
-
- ... Newspaper Ad: Dog for sale: eats anything and is fond of children.
- --
- | Fidonet: Andrew Frank 1:259/423
- | Internet: Andrew.Frank@fknights.gryn.org
-